# $Id$
# Copyright 2009 Brian Dols <dols@68k.org>, All Rights Reserved
#
#          Licensed under the Apache License, Version 2.0 (the "License");
#          you may not use this file except in compliance with the License.
#          You may obtain a copy of the License at
#
#             http://www.apache.org/licenses/LICENSE-2.0
#
#           Unless required by applicable law or agreed to in writing,
#           software distributed under the License is distributed on an
#           "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
#           KIND, either express or implied.  See the License for the
#           specific language governing permissions and limitations
#           under the License.    
#
#
from MLBviewer import MLBConfig
from MLBviewer import AUTHDIR, AUTHFILE

import os, time, datetime
import sys, urllib2

DEFAULT_V_PLAYER = 'mplayer -cache 2048 -really-quiet'
DEFAULT_A_PLAYER = 'mplayer -cache 64 -really-quiet'
DEFAULT_V_ARGS = '-cache 8192 -softvol -fixed-vo -autosync 30 -nolirc'
DEFAULT_SPEED = '800'
STREAM_SPEEDS = ( '164', '400', '600', '800', '1200', '1800', '2200', '3000' )
GUI_CONFIG="guiconfig"


def check_and_install_config():
    config={"data":None, "valid":True}
    myconfdir = os.path.join(os.environ['HOME'],AUTHDIR)
    mydefaults = {'speed': DEFAULT_SPEED,
              'video_args': DEFAULT_V_ARGS,
              'audio_player': DEFAULT_A_PLAYER,
              'audio_follow': [], 'video_follow': [],
              'blackout': [], 'favorite': [],
              'use_color': 0,
              'favorite_color': 'cyan', 'bg_color': 'xterm',
              'show_player_command': 0,
              'debug': 0,
              'x_display': '', 'top_plays_player': '',
              'time_offset': None,
              'max_bps': 800000,
              'live_from_start': 0,
              'use_nexdef': 1,
              'strict_stream': 1,
              'coverage' : 'home',
              'log_file': os.path.join(myconfdir,"guilog"),
              'mplayer_path': "/usr/bin/mplayer",
              'show_inning_frames': 1,
              'flash_browser': None }
    try:
        os.stat(myconfdir)
    except:
        os.mkdir(myconfdir)
    cursesconf =  os.path.join(myconfdir,AUTHFILE)
    guiconf =  os.path.join(myconfdir,GUI_CONFIG)
    try:
        os.stat(guiconf)
    except:
        try:
            os.stat(cursesconf)
            mlbviewerconf = MLBConfig(mydefaults)
            mlbviewerconf.loads(cursesconf)
            mlbviewerconf.write(guiconf) #copy config to our new location
        except:
            ourconf = MLBConfig(mydefaults)
            ourconf.write(guiconf)
    config['data'] = MLBConfig(mydefaults)
    config['data'].loads(guiconf)
    d = config['data'].data
    if not d.has_key('user') or not d.has_key('pass') \
       or not d.has_key('video_cache') or not d.has_key('mplayer_path'):
        config['valid'] = False
    get_schemas()
    #install autobahn, run with -Xmx1024m
    return config

def get_schemas():
    xsd_url = "http://mlbviewer.svn.sourceforge.net/viewvc/mlbviewer/trunk/MediaService.xsd"
    wsdl_url = "http://mlbviewer.svn.sourceforge.net/viewvc/mlbviewer/trunk/MediaService.wsdl"
    data = {}
    for i in ((xsd_url,"xsd"),(wsdl_url,"wsdl")):
        req = urllib2.Request(url=i[0])
        try:
            handle = urllib2.urlopen(req)
        except Exception,detail:
            error_str = 'Error occurred in HTTP request to workflow page:' + str(detail)
            raise Exception, error_str
        data[i[1]] = handle.read()
    for i in ("xsd","wsdl"):
        file = os.path.join(os.environ['HOME'], AUTHDIR, 'MediaService.%s' % i)
        update = 0
        try:
            f=open(file)
            d=f.read()
            f.close()
            if d!=data[i]:
                update = 1
        except:
            update = 1
        if update == 1:
            f=open(file,'w')
            f.write(data[i])
            f.close()
            os.system("/bin/rm -rf /tmp/suds")

def check_tuner(tuner_path, slot,expiry=3000):
    """ checks tuner to see if it is valid to overwrite the slot. if so, return True """
    valid = False
    try:
        pid_file = open("%s/%smlbtv.pid" % (tuner_path,slot))
        #pid_line = pid_file.readline()
        pid = pid_file.readline().strip()
        print "checking %s/%smlbtv.pid: %s " % (tuner_path,slot,pid)
        pid_file.close()
        try:
            os.kill(int(pid),0)
            valid = True
            print "pid %s active %s " % (pid,slot)
        except Exception, e:
            pass
        if valid:
            last_update = os.stat("%s/%smlbtv.flv" % (tuner_path,slot)).st_mtime
            print "time diff %s " % (time.time()-last_update)
            if time.time() - last_update > expiry:
                valid = False
    except Exception, e:
        pass
    return valid

def kill_tuner(tuner_path, slot):
    killed = False
    try:
        pid_file = open("%s/%smlbtv.pid" % (tuner_path,slot))
        #pid_line = pid_file.readline()
        pid = pid_file.readline().strip()
        print "killing %s/%smlbtv.pid: %s " % (tuner_path,slot,pid)
        pid_file.close()
        try:
            os.kill(int(pid),9)
            killed = True
            print "pid %s killed for slot %s" % (pid,slot)
        except Exception, e:
            pass
    except Exception, e:
        pass
    if killed:
        time.sleep(5)
        if not check_tuner(tuner_path, slot, 4):
            killed = False
    return killed


